/**
 * 材料模糊查询
 */
App.directive('stockSearch', ['$rootScope', 'Page', function ($rootScope, Page) {
    return {
        restrict: 'A',
        scope: {
            model: '@ngModel',
            stockRet: '&'
        },
        replace: true,
        require: 'ngModel',

        template: '<div>'
             + '<input type="text" class="form-control typeahead" ng-model="stockRet.stockName" placeholder="模糊查询">'
             + '</div>',

        controller: ['$scope', '$element', '$rootScope', function ($scope, $element, $rootScope) {
            $scope.codeId = Metronic.getUniqueID();
        }],

        link: function (scope, elem, attrs, ngModelController) {

            //设置id值
            $(elem).find('.typeahead:eq(0)').attr('id', 'stockSearch' + scope.codeId);

            var remote_stocks = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.obj.whitespace('stockName'),
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                remote: 'stock/queryFuzzy.do?stockName=%QUERY',
                limit: 10
            });

            remote_stocks.initialize();

            $('#stockSearch' + scope.codeId).typeahead({
                hint: false,
                highlight: true,
                minLength: 1
            }, {
                name: 'id',  //tt-dataset-id
                displayKey: 'stockName',
                source: remote_stocks.ttAdapter(),
                templates: {
                    empty: '<div class="form-control">没有找到相关数据</div>',
                    suggestion: Handlebars.compile('<span style="text-align:left;">{{stockName}}（类型：{{typeName}})（规格：{{spec}}）（单位：{{unit}}）（数量：{{num}}）</span>')
                }
            }).bind('typeahead:selected', function (obj, data) {
                ngModelController.$setViewValue(data);
                scope.stockRet();
                ngModelController.$render();
            }).bind('typeahead:opened ', function (obj, data) {
                if( obj.target.value != ''){
                    $('#stockSearch' + scope.codeId).typeahead('val', obj.target.value);
                }
            });

            // dom值为空时，viewValue置空
            elem.find('input[type="text"]').bind("input propertychange", function () {
                if( $.trim($('#stockSearch' + scope.codeId).typeahead('val')).length == 0 ) {
                    ngModelController.$setViewValue();
                }
            });

            ngModelController.$render = function () {
                if (typeof ngModelController.$viewValue != undefined) {
                    elem.find('input[type="text"]').val(ngModelController.$viewValue);
                }
            }
        }
    };
}]);
